package com.atm.servlet;

import com.atm.pojo.User;
import com.atm.service.UserService;
import com.atm.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * 添加用户
 */
@WebServlet("/insert")
public class UserAddServlet extends HttpServlet {
    private UserService userService=new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        req.setCharacterEncoding("UTF-8");
//        String icno = req.getParameter("icno");
//        String name = req.getParameter("name");
//        String mobile = req.getParameter("mobile");
//        String idcard = req.getParameter("idcard");
//        Double balance=null;
//        if (req.getParameter("balance")!=null){
//            balance  = Double.parseDouble(req.getParameter("balance"));
//        }
//        User user = new User();
//        user.setBalance(balance);
//        user.setIdcard(idcard);
//        user.setPwd("123456");
//        user.setMobile(mobile);
//        user.setName(name);
//        user.setIcno(icno);
        Map<String, String[]> parameterMap = req.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user, parameterMap);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        //设置初始密码
        user.setPwd("123456");
        //业务添加
        boolean result = userService.addUser(user);
        if (result){
            //页面显示
            resp.sendRedirect("/list");
        }else {
            resp.getOutputStream().print("添加失败");
        }
    }
}
